package kingone.phone_store_spring_practice.controller;

import kingone.phone_store_spring_practice.dto.OrderDTO;
import kingone.phone_store_spring_practice.exception.PhoneException;
import kingone.phone_store_spring_practice.form.AddressForm;
import kingone.phone_store_spring_practice.form.OrderForm;
import kingone.phone_store_spring_practice.service.OrderService;
import kingone.phone_store_spring_practice.service.PhoneService;
import kingone.phone_store_spring_practice.util.ResultVOUtil;
import kingone.phone_store_spring_practice.vo.OrderDetailVO;
import kingone.phone_store_spring_practice.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderHandler {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PhoneService phoneService;

    @PostMapping("/create")
    public ResultVO create(@Valid @RequestBody OrderForm orderForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【创建订单】参数错误，orderForm={}",orderForm);
            throw new PhoneException(bindingResult.getFieldError().getDefaultMessage());
        }

        //由于此次的表涉及到两个类OrderForm和OrderDTO,因此需要先将OrderForm中的信息转到OrderDTO
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerPhone(orderForm.getTel());
        orderDTO.setSpecsId(orderForm.getSpecsId());
        orderDTO.setPhoneQuantity(orderForm.getQuantity());

        orderService.create(orderDTO);

        //从接口文档中可以看出，返回值组data中有一个键值对存储了“orderId'信息
        Map<String, String> map = new HashMap<>();
        map.put("orderId",orderDTO.getOrderId());

        return ResultVOUtil.success(map);
    }

    @GetMapping("/detail/{orderId}")
    public ResultVO findOrderDetail(@PathVariable("orderId")String orderId){
        OrderDetailVO orderDetailByOrderId = orderService.findOrderDetailByOrderId(orderId);
        return ResultVOUtil.success(orderDetailByOrderId);
    }

    @PutMapping("/pay/{orderId}")
    public ResultVO pay(@PathVariable("orderId")String orderId){
        //修改支付状态，且返回值就是orderId
        String payOrderId = orderService.pay(orderId);
        Map<String, String> map = new HashMap<>();
        map.put("orderId",payOrderId);

        return ResultVOUtil.success(map);
    }
}
